import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

public class ModifyQuestionFrame extends JFrame {
    private JComboBox<String> questionNoComboBox;
    private JTextField questionContentField;
    private JTextField choiceAField;
    private JTextField choiceBField;
    private JTextField questionTypeField;
    private JButton updateButton;

    public ModifyQuestionFrame() {
        setTitle("MBTI职业性格测试 - 修改题目");
        setSize(400, 300);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(6, 2));

        JLabel questionNoLabel = new JLabel("题目编号:");
        panel.add(questionNoLabel);

        QuestionDAO questionDAO = new QuestionDAOImpl();
        List<Question> questions = questionDAO.getAllQuestions();
        String[] questionNos = new String[questions.size()];
        for (int i = 0, len = questions.size(); i < len; i++) {
            questionNos[i] = questions.get(i).getQNo();
        }
        questionNoComboBox = new JComboBox<>(questionNos);
        panel.add(questionNoComboBox);

        JLabel questionContentLabel = new JLabel("题目内容:");
        panel.add(questionContentLabel);

        questionContentField = new JTextField();
        panel.add(questionContentField);

        JLabel choiceALabel = new JLabel("选项A:");
        panel.add(choiceALabel);

        choiceAField = new JTextField();
        panel.add(choiceAField);

        JLabel choiceBLabel = new JLabel("选项B:");
        panel.add(choiceBLabel);

        choiceBField = new JTextField();
        panel.add(choiceBField);

        JLabel questionTypeLabel = new JLabel("题目类型:");
        panel.add(questionTypeLabel);

        questionTypeField = new JTextField();
        panel.add(questionTypeField);

        updateButton = new JButton("更新题目");
        updateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String selectedQuestionNo = (String) questionNoComboBox.getSelectedItem();
                Question question = questionDAO.findByQuestionNo(selectedQuestionNo);
                if (question!= null) {
                    question.setQContent(questionContentField.getText());
                    question.setChoiceA(choiceAField.getText());
                    question.setChoiceB(choiceBField.getText());
                    question.setQuestionType(questionTypeField.getText());
                    questionDAO.update(question);
                    JOptionPane.showMessageDialog(ModifyQuestionFrame.this, "题目更新成功！");
                } else {
                    JOptionPane.showMessageDialog(ModifyQuestionFrame.this, "未找到对应题目，请检查！", "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        panel.add(updateButton);

        add(panel);
    }
}